import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

// dom转img并pdf输出
/**
 *
 * @param canvas dom节点
 * @param pdfName pdf文件名
 * @param options 其余配置项可无
 */
export const htmlToImgPdf = async (
  canvas: HTMLElement,
  pdfName: string = 'aaa',
  options: any = {}
) => {
  // 设置放大倍数
  const scale = window.devicePixelRatio;

  // 传入节点原始宽高
  const _width = canvas.offsetWidth;
  const _height = canvas.offsetHeight;

  let { width, height } = options;
  width = width || _width;
  height = height || _height;

  // html2canvas配置项
  const ops = {
    scale,
    // width,
    // height,
    useCORS: true,
    allowTaint: false,
    // ...options
  };

  let imageData = await html2canvas(canvas, ops).then(async (canvas) => {
    // 返回图片的二进制数据
    return canvas.toDataURL('image/png');
  });
  if (height) {
    let ratio = width / height;
    toPdf(imageData, pdfName);
  }
};

const toPdf = (val: string, pdfName: string) => {
  let [imgX, imgY] = [595.28, 841.89]; // a4纸尺寸[595.28, 841.89];
  var pdfX = imgX;
  var pdfY = imgY;
  let pdf = new jsPDF('p', 'pt', [pdfX, pdfY]); //l：横向  p：纵向
  pdf.addImage(val, 'PNG', 0, 0, imgX, imgY);
  pdf.save(pdfName);
};
